package code.nest.serializer;

import code.nest.dto.Log;
import org.apache.kafka.common.serialization.Serializer;

import java.nio.ByteBuffer;
import java.util.Map;

/**
 * @author ：Hyman
 * @date ：Created in 2021/6/29 16:35
 * @description：
 * @modified By：
 * @version: $
 */
public class LogSerializer implements Serializer<Log> {

    @Override
    public void configure(Map<String, ?> map, boolean b) {

    }

    @Override
    public byte[] serialize(String s, Log log) {
        try {
            byte[] serialedContent;
            int stringSize;
            if (log == null) {
                return null;
            } else {
                if (log.getContent() != null) {
                    serialedContent = log.getContent().getBytes();
                    stringSize = serialedContent.length;
                } else {
                    serialedContent = new byte[0];
                    stringSize = 0;
                }
            }
            ByteBuffer buffer = ByteBuffer.allocate(4 + 4 + stringSize + 8);
            buffer.putInt(log.getType());
            buffer.putInt(stringSize);
            buffer.put(serialedContent);
            buffer.putLong(log.getRecordTime());
            return buffer.array();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void close() {

    }
}
